package me.rvj.entity;


import me.rvj.dao.UserDao;
import me.rvj.util.HttpSessionConfigurator;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: JavaWeb
 * @description: WebSocket
 * @author: Rv_Jiang
 * @date: 2021/6/29 9:17
 */

@ServerEndpoint("/websocket")
public class ServerSocket {

    //    属性
    private boolean flag = true;
    private String userName;

    //    正则捕获
    private static final String MSG_TO_All_REG = "all:(.+)";
    private static final String MSG_TO_OTHER_REG = "(.+):(.+)";

    //    服务器在线玩家List
    public static Map<String, User> onlineUserList = new HashMap<>();

    public static int getOnlineUserNumber() {
        return onlineUserList.size();
    }

    public static List<User> getOnlineUserList() {
        List<User> userList = new ArrayList<>();
        for (Map.Entry<String, User> userEntry : onlineUserList.entrySet()) {
            userList.add(userEntry.getValue());
        }
        return userList;
    }


    @OnOpen
    public void onOpen(Session session) {
        System.out.println(session);
    }


    @OnClose
    public void onClose() {
        onlineUserList.remove(this.userName);
        System.out.println("用户[" + this.userName + "]已退出\t当前在线[" + getOnlineUserNumber() + "]");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        if (flag) {
            firstLogin(message, session);
            flag = false;
        } else {
//            消息处理
            if (message.matches(MSG_TO_All_REG)) {
//                群发消息
                Matcher matcher = Pattern.compile(MSG_TO_All_REG).matcher(message);
                matcher.find();
                String sendMsg = matcher.group(1);
                if (sendMsg == null || sendMsg.length() == 0) {
                    try {
                        session.getBasicRemote().sendText("系统提示[" + message + "]发送失败");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    sendMsgToAll(sendMsg);
                }
            } else if (message.matches(MSG_TO_OTHER_REG)) {
//                私发消息
                Matcher matcher = Pattern.compile(MSG_TO_OTHER_REG).matcher(message);
                matcher.find();
                String target = matcher.group(1).trim();
                String sendMsg = matcher.group(2);
                if (sendMsg == null || sendMsg.length() == 0) {
                    try {
                        session.getBasicRemote().sendText("系统提示[" + message + "]发送失败");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    sendMsgToOther(target, sendMsg);
                }
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
    }


    /**
     * @description 登录记录在线信息
     * @author Rv_Jiang
     * @date 2021/7/7 20:25
     */
    public void firstLogin(String message, Session session) {
        this.userName = message;

        if (!onlineUserList.containsKey(this.userName)) {
//            页面刷新时检测在线用户会出错
            List<User> userList = UserDao.getUserList();
            for (User item : userList) {
                if (item.getUserName().equals(message)){
                    onlineUserList.put(message,item);
                }
            }
        }

        User user = onlineUserList.get(this.userName);
        user.setSession(session);
        onlineUserList.put(this.userName, user);
        System.out.println("用户[" + this.userName + "]已登录\t当前在线[" + getOnlineUserNumber() + "]");

    }

    /**
     * @description 群发消息
     * @author Rv_Jiang
     * @date 2021/7/7 20:42
     */
    public void sendMsgToAll(String msg) {
        for (Map.Entry<String, User> item : onlineUserList.entrySet()) {
            if (!this.userName.equals(item.getKey())) {
                try {
                    item.getValue().getSession().getBasicRemote().sendText("all:" + this.userName + ":" + msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @description 私发消息
     * @author Rv_Jiang
     * @date 2021/7/7 20:53
     */
    public void sendMsgToOther(String target, String msg) {
        for (Map.Entry<String, User> item : onlineUserList.entrySet()) {
            if (target.equals(item.getKey())) {
                try {
                    item.getValue().getSession().getBasicRemote().sendText("other:" + this.userName + ":" + msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}